define(function (require, exports, module) {
    var template = require("template");
    var Ajax = require("ajax");
    var layer = require("layer");
    var Echarts=require("echarts");
    require("laydate");
    var analysis = function (callback) {
        this.init.apply(this,arguments);
    };
    analysis.prototype = {
        constructor: analysis,
        options: {},
        init: function (options) {
            var t = this;
            t.options = $.extend({},t.options,options);
            $(".tipConNav").text("整体舆情分析");
            //加载整体舆情分析详情
            t.loadTotalSysis();
            //初始化
            t.changeNav();
			//滚动条置顶
			window.scrollTo(0,0);
        },
        initDate:function(){
        	function getMoreDay(dateTemp, days) {  
        	    var dateTemp = dateTemp.split("/");  
        	    var nDate = new Date(dateTemp[1] + '/' + dateTemp[2] + '/' + dateTemp[0]); //转换为MM/DD/YYYY格式    
        	    var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);  
        	    var rDate = new Date(millSeconds);
        	    var currentDate = new Date();
        	    if(rDate.getTime()>currentDate.getTime()){ //endDate的最大时间设置为当前时间
        	    	rDate = currentDate;
        	    }
        	    var year = rDate.getFullYear();  
        	    var month = rDate.getMonth() + 1;  
        	    if (month < 10) month = "0" + month;  
        	    var date = rDate.getDate();  
        	    if (date < 10) date = "0" + date;  
        	    return (year + "/" + month + "/" + date);  
        	} 
        	function getLessDay(dateTemp, days) {  
        	    var dateTemp = dateTemp.split("/");  
        	    var nDate = new Date(dateTemp[1] + '/' + dateTemp[2] + '/' + dateTemp[0]); //转换为MM/DD/YYYY格式    
        	    var millSeconds = Math.abs(nDate) - (days * 24 * 60 * 60 * 1000);  
        	    var rDate = new Date(millSeconds);  
        	    var year = rDate.getFullYear();  
        	    var month = rDate.getMonth() + 1;  
        	    if (month < 10) month = "0" + month;  
        	    var date = rDate.getDate();  
        	    if (date < 10) date = "0" + date;  
        	    return (year + "/" + month + "/" + date);  
        	} 
        	var beginDate={
    		    elem: '#beginDate',
    		    max: laydate.now(),
    		    query: function(){
//    		    	console.log(222);
    		    },
    		    choose: function(datas){
    		    	datas=datas.replace(/-/g,'/');
                    endDate.min = datas; //开始日选好后，重置结束日的最小日期
                    endDate.start = datas //将结束日的初始值设定为开始日
                    endDate.max = getMoreDay(datas,6);
                },
                done: function(value, datas, endDate){
                	datas=datas.replace(/-/g,'/');
                	 endDate.min = datas; //开始日选好后，重置结束日的最小日期
                     endDate.start = datas //将结束日的初始值设定为开始日
                     endDate.max = getMoreDay(datas,6);
                },
                reset: function (datas) {
                	datas=datas.replace(/-/g,'/');
                    endDate.min = '1900/01/01'; //重置结束日期的最小值
                    beginDate.start = laydate.now(); //将开始日期的初始值设定为今天
                },
    		};
        	var endDate={
    		    elem: '#endDate',
    		    max: laydate.now(),
    		    choose: function(datas){
    		    	datas=datas.replace(/-/g,'/');
    		    	beginDate.max = datas; //结束日选好后，重置开始日的最大日期
    		    	beginDate.min = getLessDay(datas,6);
                },
                done: function(value, datas, beginDate){
                	datas=datas.replace(/-/g,'/');
    		    	beginDate.max = datas; //结束日选好后，重置开始日的最大日期
    		    	beginDate.min = getLessDay(datas,6);
                },
                reset: function () {
                	beginDate.max = laydate.now(); //设置开始日期最大值
                    endDate.start = laydate.now(); //将结束日期的初始值设定为今天
                    beginDate.min = '1900/01/01';  //清空结束日后，重置开始日的最小时间
                },
    		};
        	//开始日期
            $("#beginDate").click(function(){
                laydate(beginDate);
            });
            
            //结束日期
            $("#endDate").click(function(){
                laydate(endDate);
            });
        },
        changeNav:function(){
        	var t=this;
        	$('.navBox li').on('click',function(){
        		if(!$(this).hasClass('current')){
        			$(this).addClass('current').siblings('li').removeClass('current');
        		}
        	});
        	$(".navBox li:eq(0)").on('click',function(){
        		$(".tipConNav").text("整体舆情分析");
        		t.loadTotalSysis();
        	});
        	$(".navBox li:eq(1)").on('click',function(){
        		$(".tipConNav").text("网络舆情分析");
        		//加载网络舆情分析
				t.loadNetSysis();
        	});
        	$(".navBox li:eq(2)").on('click',function(){
        		$(".tipConNav").text("媒体舆情分析");
        		//加载媒体舆情分析
				t.loadMediaSysis();
        	});
        },
        loadTotalSysis:function(){
        	var t=this;
        	$(".contentBox").html(template("totalTemp",{}));
        	//初始化日期插件
            t.initDate();
            //加载列表
            t.loadTotalList($('#beginDate').val(),$('#endDate').val());
            $('.searchBtn').on('click',function(){
            	var bDate=$('#beginDate').val();
                var eDate=$('#endDate').val();
                t.loadTotalList(bDate,eDate);
            });
        },
        loadTotalList:function(bDate,eDate){
        	var t=this;
    	    var beginDate = new Date(bDate); 
    	    var bDateVal = Math.abs(beginDate);
    	    var bDates = new Date(bDateVal);
    	    var endDate = new Date(eDate); 
    	    var eDateVal = Math.abs(endDate);
    	    var eDates = new Date(eDateVal);
    	    if((bDate && !eDate)||(!bDate && eDate)||(bDates.getTime()>eDates.getTime())){
    	    	layer.msg('起止时间范围有误，请重新选择！');
            	return false;
    	    }
    	    if(eDates-bDates>518400000){
    	    	layer.msg('时间范围仅限于7天！');
            	return false;
    	    }
        	if(bDate!=''&&eDate!=''){
        		var timePhase=bDate.substring(0,4)+'/'+bDate.substring(5,7)+'/'+bDate.substring(8,10)+' - '+eDate.substring(0,4)+'/'+eDate.substring(5,7)+'/'+eDate.substring(8,10);
        	}
        	var totalArr=[],positiveArr=[],negativeArr=[],dateArr=[];
       	 	Ajax.ajax({
                url:localhost + "analysis/wholeSentiment.do",
                data:{timePhase:timePhase,endDate:eDate,starDate:bDate},
                beforeSend:function(){
                	$(".tbody").html("<div class='loadingBox animated fadeIn nextloding'><span>正在加载中，请稍后</span></div>");
                	$(".picBox").hide();
                },
                success:function(data){
                	var href = window.location.href.indexOf("admin/analysis");
    				if(href < 0 ) {
    					return;
    				}
                	var item=data.returnData;
                	$('.tbody').html('');
                	if(item.length>0){
                		for(var i=0;i<item.length;i++){
                    		$('.tbody').append(template('liTemp',item[i]));
                    		totalArr.push(item[i].number);
                    		positiveArr.push(item[i].positiveNumber);
                    		negativeArr.push(item[i].negativeNumber);
                    		dateArr.push(item[i].date);
                    	}
                		$(".picBox").show();
                		//加载折线图
                   	 	if(bDate!=eDate){
                   	 		$(".lineBox").css("display","block");
                   	 		$(".pieTypesBox").css("display","none");
                   	 		t.loadLinePic(totalArr,positiveArr,negativeArr,dateArr);
                   	 	}else{
                   	 		if(bDate==""){
                   	 			bDate=t.getDateStr();
                   	 			eDate=t.getDateStr();
                   	 		}
                   	 		$(".lineBox").css("display","none");
                   	 		$(".pieTypesBox").css("display","block");
                   	 		var bbsArr=[],microArr=[],newsArr=[],weixinArr=[];
	                   	 	Ajax.ajax({
	                            url:localhost + "analysis/distribution.do",
	                            data:{timePhase:timePhase,endDate:eDate,starDate:bDate},
	                            success:function(datas){
	                            	var items=datas.returnData;
                            		bbsArr.push(items.BBS);
                            		microArr.push(items.Micro);
                            		newsArr.push(items.News);
                            		weixinArr.push(items.WeiXin);
                            		//加载饼状图
                            		t.loadPieTypesPic(bbsArr,microArr,newsArr,weixinArr,dateArr);
	                            }
	                        });
                   	 	}
                        //加载饼状图
                        t.loadPiePic(totalArr,positiveArr,negativeArr,dateArr);
                	}else{
                		$('.tbody').html(template('noDataDom'));
                	}
                }
            });
        },
		//获取当前的时间
		getDateStr: function(){
			var curDate = new Date();
			curDate.setDate(curDate.getDate());
			var y = curDate.getFullYear();
			var m = curDate.getMonth()+1;
			var d = curDate.getDate();
			return y+'-'+m+'-'+d;
		},
        loadNetSysis:function(){
        	var t=this;
        	$(".contentBox").html(template("netTemp",{}));
        	//初始化日期插件
            t.initDate();
            //加载列表
            t.loadNetList($('#beginDate').val(),$('#endDate').val());
            //切换类别
            $('.wayBox .iconfont').on('click',function(){
            	if($(this).hasClass('checked')){
            		$(this).removeClass('checked').removeClass('icon-check').addClass('icon-fangxingweixuanzhong');
            	}else{
            		$(this).removeClass('icon-fangxingweixuanzhong').addClass('icon-check').addClass('checked');
            	}
            });
            $('.searchBtn').on('click',function(){
            	var bDate=$('#beginDate').val();
                var eDate=$('#endDate').val();
                t.loadNetList(bDate,eDate);
            });
        },
        loadNetList:function(bDate,eDate){
        	var t=this;
    	    var beginDate = new Date(bDate); 
    	    var bDateVal = Math.abs(beginDate);
    	    var bDates = new Date(bDateVal);
    	    var endDate = new Date(eDate); 
    	    var eDateVal = Math.abs(endDate);
    	    var eDates = new Date(eDateVal);
    	    if((bDate && !eDate)||(!bDate && eDate)||(bDates.getTime()>eDates.getTime())){
    	    	layer.msg('起止时间范围有误，请重新选择！');
            	return false;
    	    }
    	    if(eDates-bDates>518400000){
    	    	layer.msg('时间范围仅限于7天！');
            	return false;
    	    }
        	if(bDate!=''&&eDate!=''){
        		var timePhase=bDate.substring(0,4)+'/'+bDate.substring(5,7)+'/'+bDate.substring(8,10)+' - '+eDate.substring(0,4)+'/'+eDate.substring(5,7)+'/'+eDate.substring(8,10);
        	}
        	var articleTypesArr=[];
        	for(var i=0;i<3;i++){
        		if($($('.wayBox .iconfont')[i]).hasClass('checked')){
        			var wayId=$($('.wayBox .iconfont')[i]).attr('data-id');
        			articleTypesArr.push(wayId);
            	}
        	}
        	var articleTypes=articleTypesArr.join(',');
        	if(!articleTypes && window.location.href.indexOf("admin/analysis")>-1){
        		layer.msg('论坛、微信、微博，请至少选择一项！',{time:1000},function(){});
        		return false;
        	}
        	
        	var totalArr=[],positiveArr=[],negativeArr=[],dateArr=[];
       	 	Ajax.ajax({
                url:localhost + "analysis/networkSentiment.do",
                data:{timePhase:timePhase,endDate:eDate,starDate:bDate,articleTypes:articleTypes},
                beforeSend:function(){
                	$(".tbody").html("<div class='loadingBox animated fadeIn nextloding'><span>正在加载中，请稍后</span></div>");
                	$(".picBox").hide();
                },
                success:function(data){
                	var href = window.location.href.indexOf("admin/analysis");
    				if(href < 0 ) {
    					return;
    				}
                	var item=data.returnData;
                	$('.tbody').html('');
                	if(item.length>0){
                		for(var i=0;i<item.length;i++){
                    		$('.tbody').append(template('liTemp',item[i]));
                    		totalArr.push(item[i].number);
                    		positiveArr.push(item[i].positiveNumber);
                    		negativeArr.push(item[i].negativeNumber);
                    		dateArr.push(item[i].date);
                    	}
                		$(".picBox").show();
                		//加载折线图
                   	 	if(bDate!=eDate){
                   	 		$(".lineBox").css("display","block");
                   	 		t.loadLinePic(totalArr,positiveArr,negativeArr,dateArr);
                   	 	}else{
                   	 		$(".lineBox").css("display","none");
                   	 	}
                        //加载饼状图
                        t.loadPiePic(totalArr,positiveArr,negativeArr,dateArr);
                	}else{
                		$('.tbody').html(template('noDataDom'));
                	}
                }
            });
        },
        loadMediaSysis:function(){
        	var t=this;
        	$(".contentBox").html(template("mediaTemp",{}));
        	//初始化日期插件
            t.initDate();
            //加载列表
            t.loadMediaList($('#beginDate').val(),$('#endDate').val());
            $('.searchBtn').on('click',function(){
            	var bDate=$('#beginDate').val();
                var eDate=$('#endDate').val();
                t.loadMediaList(bDate,eDate);
            });
        },
        loadMediaList:function(bDate,eDate){
        	var t=this;
    	    var beginDate = new Date(bDate); 
    	    var bDateVal = Math.abs(beginDate);
    	    var bDates = new Date(bDateVal);
    	    var endDate = new Date(eDate); 
    	    var eDateVal = Math.abs(endDate);
    	    var eDates = new Date(eDateVal);
    	    if((bDate && !eDate)||(!bDate && eDate)||(bDates.getTime()>eDates.getTime())){
    	    	layer.msg('起止时间范围有误，请重新选择！');
            	return false;
    	    }
    	    if(eDates-bDates>518400000){
    	    	layer.msg('时间范围仅限于7天！');
            	return false;
    	    }
        	if(bDate!=''&&eDate!=''){
        		var timePhase=bDate.substring(0,4)+'/'+bDate.substring(5,7)+'/'+bDate.substring(8,10)+' - '+eDate.substring(0,4)+'/'+eDate.substring(5,7)+'/'+eDate.substring(8,10);
        	}
        	var totalArr=[],positiveArr=[],negativeArr=[],dateArr=[];
       	 	Ajax.ajax({
                url:localhost + "analysis/mediaSentiment.do",
                data:{timePhase:timePhase,endDate:eDate,starDate:bDate},
                beforeSend:function(){
                	$(".tbody").html("<div class='loadingBox animated fadeIn nextloding'><span>正在加载中，请稍后</span></div>");
                	$(".picBox").hide();
                },
                success:function(data){
                	var href = window.location.href.indexOf("admin/analysis");
    				if(href < 0 ) {
    					return;
    				}
                	var item=data.returnData;
                	$('.tbody').html('');
                	if(item.length>0){
                		for(var i=0;i<item.length;i++){
                    		$('.tbody').append(template('liTemp',item[i]));
                    		totalArr.push(item[i].number);
                    		positiveArr.push(item[i].positiveNumber);
                    		negativeArr.push(item[i].negativeNumber);
                    		dateArr.push(item[i].date);
                    	}
                		$(".picBox").show();
                		//加载折线图
                   	 	if(bDate!=eDate){
                   	 		$(".lineBox").css("display","block");
                   	 		t.loadLinePic(totalArr,positiveArr,negativeArr,dateArr);
                   	 	}else{
                   	 		$(".lineBox").css("display","none");
                   	 	}
                        //加载饼状图
                        t.loadPiePic(totalArr,positiveArr,negativeArr,dateArr);
                	}else{
                		$('.tbody').html(template('noDataDom'));
                	}
                }
            });
        },
        loadLinePic:function(totalArr,positiveArr,negativeArr,dateArr){
        	var lineChart = echarts.init(document.getElementById('lineChartDom'));
        	option = {
        		    tooltip : {
        		        trigger: 'axis'
        		    },
        		    legend: {
        		    	data:[{
        		    		name: '正面',
	          		        icon: 'line',
	          		        textStyle: {
	          		        	color: '#494949',
	          		        }
        		    	},{
        		    		name: '负面',
	          		        icon: 'line',
	          		        textStyle: {
	          		        	color: '#494949',
	          		        }	
        		    	},{
        		    		name: '整体',
	          		        icon: 'line',
	          		        textStyle: {
	          		      		color: '#494949',
	          		        }
        		    	}]
        		    },
        		    toolbox: {
        		        show : false,
        		    },
        		    calculable : true,
        		    color:[
    			           '#98DD35',
    			           '#F44336',
    			           '#FFD600',
    		           ],
        		    xAxis : [
        		        {
        		            type : 'category',
        		            boundaryGap : false,
        		            data : dateArr
        		        }
        		    ],
        		    yAxis : [
        		        {
        		            type : 'value'
        		        }
        		    ],
        		    series : [
        		        {
        		            name:'正面',
        		            type:'line',
        		            data:positiveArr
        		        },
        		        {
        		            name:'负面',
        		            type:'line',
        		            data:negativeArr
        		        },
        		        {
        		            name:'整体',
        		            type:'line',
        		            data:totalArr
        		        }
        		    ]
        		};
        	lineChart.setOption(option);
        },
        
        loadPiePic:function(totalArr,positiveArr,negativeArr,dateArr){
        	var pieChart = echarts.init(document.getElementById('pieChartDom'));
        	var totalNum=0,positiveNum=0,negativeNum=0;
        	for(var x=0;x<totalArr.length;x++){
        		totalNum+=parseInt(totalArr[x]);
        		positiveNum+=parseInt(positiveArr[x]);
        		negativeNum+=parseInt(negativeArr[x]);
        	}
        	option = {
        		    title : {
        		        text: '',
        		        subtext: '',
        		        x:'center'
        		    },
        		    tooltip : {
        		        trigger: 'item',
        		        formatter: "{a} <br/>{b} : {c} ({d}%)"
        		    },
        		    legend: {
        		        orient : 'vertical',
        		        icon:'line',
        		        right:'0',
          		        width:'30',
          		        bottom:'50',
        		        data:['负面','正面']
        		    },
        		    color:[
    			           '#98DD35',
    			           '#F44336',
    		           ],
        		    toolbox: {
        		        show : false,
        		    },
        		    calculable : true,
        		    series : [
        		        {
        		            name:'',
        		            type:'pie',
        		            radius : '55%',
        		            center: ['50%', '60%'],
        		            data:[
        		                {value:positiveNum, name:'正面'},
        		                {value:negativeNum, name:'负面'},
        		            ]
        		        }
        		    ]
        		};
        	pieChart.setOption(option);	                    
        },
        
        loadPieTypesPic:function(bbsArr,microArr,newsArr,weixinArr,dateArr){
        	var pieChart = echarts.init(document.getElementById('pieTypesChartDom'));
        	var bbsArrNum=0,microNum=0,newsNum=0,weixinNum=0;
    		bbsNum=parseInt(bbsArr[0]);
    		microNum=parseInt(microArr[0]);
    		newsNum=parseInt(newsArr[0]);
    		weixinNum=parseInt(weixinArr[0]);
        	option = {
        		    title : {
        		        text: '',
        		        subtext: '',
        		        x:'center'
        		    },
        		    tooltip : {
        		        trigger: 'item',
        		        formatter: "{a} <br/>{b} : {c} ({d}%)"
        		    },
        		    legend: {
        		        orient : 'vertical',
        		        icon:'line',
        		        right:'0',
          		        width:'30',
          		        bottom:'50',
        		        data:['论坛','微博','新闻','微信']
        		    },
        		    color:[
        		         '#3EBFBE',
        		         '#FFB553',
        		         '#DB5D4F',
        		         '#8078D7'
        		    ],
        		    toolbox: {
        		        show : false,
        		    },
        		    calculable : true,
        		    series : [
        		        {
        		            name:'',
        		            type:'pie',
        		            radius : '55%',
        		            center: ['50%', '60%'],
        		            data:[
        		                {value:bbsNum, name:'论坛'},
        		                {value:microNum, name:'微博'},
        		                {value:newsNum, name:'新闻'},
        		                {value:weixinNum, name:'微信'},
        		            ]
        		        }
        		    ]
        		};
        	pieChart.setOption(option);	                    
        }
    };
    module.exports = analysis;
});